package online_exams.controller;

import cn.dev33.satoken.secure.BCrypt;
import cn.dev33.satoken.stp.StpUtil;
import online_exams.domain.TUserEntity;
import online_exams.service.AdminService;
import online_exams.service.TUserService;
import online_exams.utils.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.io.Serializable;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 用户信息表(TUser)表控制层
 *
 * @author makejava
 * @since 2024-12-19 16:49:59
 */
@RestController
@RequestMapping("/admin")
public class AdminController {
    /**
     * 服务对象
     */
    @Autowired
    private AdminService adminService;

    /**
     * 管理员添加用户
     * @param user
     * @return
     */
    @PutMapping("/addUser")
    public Result addUser(@RequestBody TUserEntity tUserEntity) {
        // 处理空字符串
        if ("".equals(tUserEntity.getPhone())) {
            tUserEntity.setPhone(null);
        }
        if ("".equals(tUserEntity.getEmail())) {
            tUserEntity.setEmail(null);
        }
        System.out.println(tUserEntity);
        TUserEntity GetUser = adminService.getUser(tUserEntity);
        try {
            if (GetUser != null) { // 检查工号、学号重复
                // 检查邮箱重复
                if (tUserEntity.getEmail() != null &&
                        GetUser.getEmail() != null &&
                        GetUser.getEmail().equals(tUserEntity.getEmail())) {
                    return Result.error("邮箱已被使用");
                }
                // 检查手机号重复
                if (tUserEntity.getPhone() != null &&
                        GetUser.getPhone() != null &&
                        GetUser.getPhone().equals(tUserEntity.getPhone())) {
                    return Result.error("手机号已被使用");
                }
                return Result.error("工号或学号已被使用");
            }
            Integer AddUser = adminService.addUser(tUserEntity);
            if (AddUser == 1) {
                return Result.success();
            }
            return Result.error("添加失败");
        }catch (Exception e) {
            // 处理数据库唯一约束异常
            if (e.getCause() instanceof java.sql.SQLIntegrityConstraintViolationException) {
                String message = e.getCause().getMessage();
                if (message.contains("email")) {
                    return Result.error("邮箱已被使用");
                } else if (message.contains("phone")) {
                    return Result.error("手机号已被使用");
                } else if (message.contains("id_number")) {
                    return Result.error("工号或学号已被使用");
                }
            }
            // 其他未知错误
            return Result.error("添加用户失败：" + e.getMessage());
        }
    }

    /**
     * 查询用户列表
     * @param tUserEntity
     * @return
     */
    @GetMapping("/getUserList")
    public Result<Map<String,Object>> getUserList(
            @RequestParam(required = false) String role,
            @RequestParam(required = false) String realName,
            @RequestParam(required = false) String idNumber,
            @RequestParam(defaultValue = "1") Integer currentPage,
            @RequestParam(defaultValue = "5") Integer pageSize) {
        try {
            // 创建查询实体
            TUserEntity searchEntity = new TUserEntity();
            searchEntity.setRole(role);
            searchEntity.setRealName(realName);
            searchEntity.setIdNumber(idNumber);

            // 计算偏移量
            int offset = (currentPage - 1) * pageSize;

            // 获取总记录数
            int total = adminService.getUserTotal(searchEntity);

            // 获取分页数据
            List<TUserEntity> userList = adminService.getUserListPage(searchEntity, offset, pageSize);

            // 构建返回结果
            Map<String, Object> map = new HashMap<>();
            map.put("records", userList);
            map.put("total", total);
            map.put("pageSize", pageSize);
            map.put("currentPage", currentPage);

            return Result.success(map);
        } catch (Exception e) {
            return Result.error("查询用户列表失败：" + e.getMessage());
        }
    }


    /**
     * 重置密码
     * @param tUserEntity
     * @return
     */
    @PutMapping("/updatePassword")
    public Result updatePasswordr(@RequestBody TUserEntity tUserEntity) {
        System.out.println(tUserEntity);
        tUserEntity.setPassword("123456");
        TUserEntity paswrd= adminService.getUser(tUserEntity);
        System.out.println(paswrd);
        if (BCrypt.checkpw(tUserEntity.getPassword(),paswrd.getPassword())){
            return Result.error("默认密码无需重置");
        }
        Integer updateP= adminService.updatePassword(tUserEntity);
        if (updateP == 1){
            return Result.success("重置成功");
        }
            return Result.error("重置失败");
    }

    @PutMapping("/updateUser")
    public Result UpdateUser(@RequestBody TUserEntity tUserEntity) {
        Integer updateP= adminService.updateUser(tUserEntity);
        if(updateP == 1){
            return Result.success("修改成功");
        }
        return Result.error("修改失败");
    }
}


